package com.sne.airways.system.service.impl;

import com.sne.airways.system.acl.Session;
import com.sne.airways.basecore.exceptions.AppException;
import com.sne.airways.basecore.service.impl.BaseServiceImpl;
import com.sne.airways.system.pojo.TdSubsection;
import com.sne.airways.system.utils.AppUtils;
import com.sne.airways.basecore.utils.PasswordHelper;
import com.sne.airways.system.constants.StatusType;
import com.sne.airways.system.dao.LoginDAO;
import com.sne.airways.system.pojo.TdUser;
import com.sne.airways.system.service.LoginService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created with IntelliJ IDEA.
 * User: skyline{http://my.oschina.net/skyline520}
 * Date: 12-11-16
 * Time: 下午5:39
 * To change this template use File | Settings | File Templates.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class LoginServiceImpl extends BaseServiceImpl implements LoginService {
    @Autowired
    private LoginDAO loginDAO;
    /**
     * 根据用户登录号和密码进行用户登录操作
     *
     * @param userNo
     * @param password
     * @throws com.sne.airways.basecore.exceptions.AppException
     *
     */
    @Override
    public void processLogin(String userNo, String password) throws AppException {

        if(StringUtils.isBlank(userNo) || StringUtils.isBlank(password)){
            throw new AppException("请完整填写用户名与密码!");
        }
        TdUser tdUser = loginDAO.queryUserObj(StringUtils.trimToEmpty(userNo));
        if(tdUser == null){
            throw new AppException("不存在的账户["+userNo+"]!");
        }
        if(StatusType.冻结.getValue().equals(tdUser.getStatus())){
            throw new AppException("账户["+userNo+"]已被冻结!");
        }
        String encodePassword = PasswordHelper.encodePassword(password);
        if(!StringUtils.equals(encodePassword,tdUser.getPassword())){
            throw new AppException("账户密码错误!");
        }
        //初始化用户缓存信息
        initSession(tdUser,tdUser.getSubsectionId());
    }

    /**
     * 用户退出登录
     *
     * @throws com.sne.airways.basecore.exceptions.AppException
     *
     */
    @Override
    public void processLogout() throws AppException {
        AppUtils.getSessionCache().removeIt(AppUtils.getRequest().getSession().getId());
        AppUtils.getRequest().getSession().invalidate();
        logger.info("[用户信息]从缓存中移除");
    }

    private void initSession(TdUser user,TdSubsection subsection){
        Session session = new Session();
        session.setUser(user);
        session.setIp(AppUtils.getRemoteAddr());
        session.setSubsection(subsection);
        //用户登录信息存入缓存
        AppUtils.getSessionCache().put(AppUtils.getRequest().getSession().getId(), session);
        logger.info("[用户信息]已经成功放入缓存");
    }
}
